<template>
  <div class="model-evaluation">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>模型评估与部署</span>
          <el-button-group>
            <el-button type="primary" @click="handleCompare">
              <el-icon><Compare /></el-icon>模型对比
            </el-button>
            <el-button type="success" @click="handleDeploy">
              <el-icon><Upload /></el-icon>部署模型
            </el-button>
          </el-button-group>
        </div>
      </template>

      <el-tabs v-model="activeTab">
        <!-- 模型列表 -->
        <el-tab-pane label="模型列表" name="list">
          <el-table :data="models" style="width: 100%">
            <el-table-column prop="name" label="模型名称" min-width="150" />
            <el-table-column prop="type" label="模型类型" width="120" />
            <el-table-column prop="version" label="版本" width="100" />
            <el-table-column prop="accuracy" label="准确率" width="120">
              <template #default="{ row }">
                {{ (row.accuracy * 100).toFixed(2) }}%
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)">
                  {{ row.status }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="更新时间" width="180" />
            <el-table-column label="操作" width="300" fixed="right">
              <template #default="{ row }">
                <el-button-group>
                  <el-button type="primary" link @click="handleEvaluate(row)">
                    评估
                  </el-button>
                  <el-button type="primary" link @click="handleViewDetails(row)">
                    详情
                  </el-button>
                  <el-button
                    type="success"
                    link
                    :disabled="row.status === 'deployed'"
                    @click="handleDeployModel(row)"
                  >
                    部署
                  </el-button>
                  <el-button type="danger" link @click="handleDelete(row)">
                    删除
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>

        <!-- 模型评估 -->
        <el-tab-pane label="模型评估" name="evaluation">
          <div class="evaluation-content" v-if="selectedModel">
            <el-row :gutter="20">
              <!-- 性能指标 -->
              <el-col :span="12">
                <el-card class="metrics-card">
                  <template #header>
                    <div class="card-header">
                      <span>性能指标</span>
                      <el-radio-group v-model="metricsType" size="small">
                        <el-radio-button label="classification">分类指标</el-radio-button>
                        <el-radio-button label="regression">回归指标</el-radio-button>
                      </el-radio-group>
                    </div>
                  </template>
                  <el-descriptions :column="1" border>
                    <el-descriptions-item label="准确率">
                      {{ (selectedModel.accuracy * 100).toFixed(2) }}%
                    </el-descriptions-item>
                    <el-descriptions-item label="精确率">
                      {{ (selectedModel.precision * 100).toFixed(2) }}%
                    </el-descriptions-item>
                    <el-descriptions-item label="召回率">
                      {{ (selectedModel.recall * 100).toFixed(2) }}%
                    </el-descriptions-item>
                    <el-descriptions-item label="F1分数">
                      {{ selectedModel.f1Score.toFixed(2) }}
                    </el-descriptions-item>
                    <el-descriptions-item label="AUC">
                      {{ selectedModel.auc.toFixed(2) }}
                    </el-descriptions-item>
                  </el-descriptions>
                </el-card>
              </el-col>

              <!-- 混淆矩阵 -->
              <el-col :span="12">
                <el-card class="confusion-matrix">
                  <template #header>
                    <div class="card-header">
                      <span>混淆矩阵</span>
                      <el-button-group>
                        <el-button type="primary" link @click="handleExportMatrix">
                          <el-icon><Download /></el-icon>导出
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div ref="confusionMatrixRef" class="matrix-container"></div>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="mt-20">
              <!-- ROC曲线 -->
              <el-col :span="12">
                <el-card class="roc-curve">
                  <template #header>
                    <div class="card-header">
                      <span>ROC曲线</span>
                      <el-button-group>
                        <el-button type="primary" link @click="handleExportROC">
                          <el-icon><Download /></el-icon>导出
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div ref="rocCurveRef" class="curve-container"></div>
                </el-card>
              </el-col>

              <!-- 特征重要性 -->
              <el-col :span="12">
                <el-card class="feature-importance">
                  <template #header>
                    <div class="card-header">
                      <span>特征重要性</span>
                      <el-button-group>
                        <el-button type="primary" link @click="handleExportImportance">
                          <el-icon><Download /></el-icon>导出
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div ref="importanceChartRef" class="importance-container"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>

        <!-- 模型对比 -->
        <el-tab-pane label="模型对比" name="comparison">
          <div class="comparison-content">
            <el-row :gutter="20">
              <!-- 模型选择 -->
              <el-col :span="24">
                <el-card class="model-selection">
                  <template #header>
                    <div class="card-header">
                      <span>选择对比模型</span>
                      <el-button type="primary" @click="handleAddModel">
                        <el-icon><Plus /></el-icon>添加模型
                      </el-button>
                    </div>
                  </template>
                  <el-table :data="comparisonModels" style="width: 100%">
                    <el-table-column type="selection" width="55" />
                    <el-table-column prop="name" label="模型名称" />
                    <el-table-column prop="type" label="模型类型" />
                    <el-table-column prop="version" label="版本" />
                    <el-table-column prop="accuracy" label="准确率">
                      <template #default="{ row }">
                        {{ (row.accuracy * 100).toFixed(2) }}%
                      </template>
                    </el-table-column>
                    <el-table-column label="操作" width="100">
                      <template #default="{ row }">
                        <el-button
                          type="danger"
                          link
                          @click="handleRemoveModel(row)"
                        >
                          移除
                        </el-button>
                      </template>
                    </el-table-column>
                  </el-table>
                </el-card>
              </el-col>
            </el-row>

            <el-row :gutter="20" class="mt-20">
              <!-- 性能对比 -->
              <el-col :span="24">
                <el-card class="performance-comparison">
                  <template #header>
                    <div class="card-header">
                      <span>性能对比</span>
                      <el-button-group>
                        <el-button type="primary" link @click="handleExportComparison">
                          <el-icon><Download /></el-icon>导出
                        </el-button>
                      </el-button-group>
                    </div>
                  </template>
                  <div ref="comparisonChartRef" class="comparison-container"></div>
                </el-card>
              </el-col>
            </el-row>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 部署对话框 -->
    <el-dialog
      v-model="deployDialogVisible"
      title="部署模型"
      width="600px"
    >
      <el-form
        ref="deployFormRef"
        :model="deployForm"
        :rules="deployRules"
        label-width="120px"
      >
        <el-form-item label="部署环境" prop="environment">
          <el-select v-model="deployForm.environment" placeholder="请选择部署环境">
            <el-option label="生产环境" value="production" />
            <el-option label="测试环境" value="testing" />
            <el-option label="开发环境" value="development" />
          </el-select>
        </el-form-item>
        <el-form-item label="资源限制" prop="resources">
          <el-input-number
            v-model="deployForm.resources.cpu"
            :min="1"
            :max="16"
            label="CPU核心数"
          />
          <el-input-number
            v-model="deployForm.resources.memory"
            :min="1"
            :max="32"
            label="内存(GB)"
          />
        </el-form-item>
        <el-form-item label="自动扩缩容">
          <el-switch v-model="deployForm.autoScaling" />
        </el-form-item>
        <el-form-item
          v-if="deployForm.autoScaling"
          label="扩缩容配置"
        >
          <el-input-number
            v-model="deployForm.scaling.minInstances"
            :min="1"
            label="最小实例数"
          />
          <el-input-number
            v-model="deployForm.scaling.maxInstances"
            :min="1"
            :max="10"
            label="最大实例数"
          />
        </el-form-item>
        <el-form-item label="部署说明">
          <el-input
            v-model="deployForm.description"
            type="textarea"
            rows="3"
            placeholder="请输入部署说明"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deployDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleDeploySubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import * as echarts from 'echarts'
import {
  Compare,
  Upload,
  Download,
  Plus
} from '@element-plus/icons-vue'

// 标签页
const activeTab = ref('list')

// 模型数据
const models = ref([
  {
    id: 1,
    name: '设备故障预测模型',
    type: 'XGBoost',
    version: 'v1.2.0',
    accuracy: 0.95,
    precision: 0.94,
    recall: 0.93,
    f1Score: 0.935,
    auc: 0.96,
    status: 'trained',
    updateTime: '2024-03-17 10:00:00'
  },
  {
    id: 2,
    name: '能耗预测模型',
    type: 'LSTM',
    version: 'v1.1.0',
    accuracy: 0.92,
    precision: 0.91,
    recall: 0.90,
    f1Score: 0.905,
    auc: 0.93,
    status: 'deployed',
    updateTime: '2024-03-16 15:30:00'
  }
])

// 选中的模型
const selectedModel = ref(null)

// 评估相关
const metricsType = ref('classification')
const confusionMatrixRef = ref(null)
const rocCurveRef = ref(null)
const importanceChartRef = ref(null)
let confusionMatrixChart = null
let rocCurveChart = null
let importanceChart = null

// 对比相关
const comparisonModels = ref([])
const comparisonChartRef = ref(null)
let comparisonChart = null

// 部署相关
const deployDialogVisible = ref(false)
const deployFormRef = ref(null)
const deployForm = reactive({
  environment: '',
  resources: {
    cpu: 2,
    memory: 4
  },
  autoScaling: false,
  scaling: {
    minInstances: 1,
    maxInstances: 3
  },
  description: ''
})

const deployRules = {
  environment: [
    { required: true, message: '请选择部署环境', trigger: 'change' }
  ]
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    trained: 'info',
    deployed: 'success',
    failed: 'danger'
  }
  return statusMap[status] || 'info'
}

// 初始化图表
onMounted(() => {
  // 初始化混淆矩阵
  confusionMatrixChart = echarts.init(confusionMatrixRef.value)
  const confusionMatrixOption = {
    tooltip: {
      position: 'top'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: ['预测正常', '预测故障'],
      splitArea: {
        show: true
      }
    },
    yAxis: {
      type: 'category',
      data: ['实际正常', '实际故障'],
      splitArea: {
        show: true
      }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%'
    },
    series: [{
      name: '混淆矩阵',
      type: 'heatmap',
      data: [
        [0, 0, 85],
        [0, 1, 5],
        [1, 0, 8],
        [1, 1, 2]
      ],
      label: {
        show: true
      },
      emphasis: {
        itemStyle: {
          shadowBlur: 10,
          shadowColor: 'rgba(0, 0, 0, 0.5)'
        }
      }
    }]
  }
  confusionMatrixChart.setOption(confusionMatrixOption)

  // 初始化ROC曲线
  rocCurveChart = echarts.init(rocCurveRef.value)
  const rocCurveOption = {
    tooltip: {
      trigger: 'axis'
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      name: '假阳性率'
    },
    yAxis: {
      type: 'value',
      name: '真阳性率'
    },
    series: [{
      name: 'ROC曲线',
      type: 'line',
      data: [
        [0, 0],
        [0.1, 0.4],
        [0.2, 0.6],
        [0.3, 0.75],
        [0.4, 0.85],
        [0.5, 0.9],
        [0.6, 0.93],
        [0.7, 0.95],
        [0.8, 0.97],
        [0.9, 0.98],
        [1, 1]
      ],
      smooth: true,
      areaStyle: {
        opacity: 0.3
      }
    }]
  }
  rocCurveChart.setOption(rocCurveOption)

  // 初始化特征重要性图表
  importanceChart = echarts.init(importanceChartRef.value)
  const importanceOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 1
    },
    yAxis: {
      type: 'category',
      data: ['温度', '湿度', '压力', '振动']
    },
    series: [{
      name: '特征重要性',
      type: 'bar',
      data: [0.4, 0.3, 0.2, 0.1],
      itemStyle: {
        color: function(params) {
          const colorList = [
            '#36a2eb',
            '#4bc0c0',
            '#9966ff',
            '#ff9f40'
          ]
          return colorList[params.dataIndex]
        }
      }
    }]
  }
  importanceChart.setOption(importanceOption)

  // 初始化对比图表
  comparisonChart = echarts.init(comparisonChartRef.value)
  const comparisonOption = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['准确率', '精确率', '召回率', 'F1分数']
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'value',
      max: 1
    },
    yAxis: {
      type: 'category',
      data: ['模型1', '模型2']
    },
    series: [
      {
        name: '准确率',
        type: 'bar',
        data: [0.95, 0.92]
      },
      {
        name: '精确率',
        type: 'bar',
        data: [0.94, 0.91]
      },
      {
        name: '召回率',
        type: 'bar',
        data: [0.93, 0.90]
      },
      {
        name: 'F1分数',
        type: 'bar',
        data: [0.935, 0.905]
      }
    ]
  }
  comparisonChart.setOption(comparisonOption)
})

// 处理函数
const handleEvaluate = (model) => {
  selectedModel.value = model
  activeTab.value = 'evaluation'
}

const handleViewDetails = (model) => {
  // TODO: 实现查看详情功能
  ElMessage.info('查看详情功能开发中...')
}

const handleDeployModel = (model) => {
  deployDialogVisible.value = true
  Object.assign(deployForm, {
    environment: '',
    resources: {
      cpu: 2,
      memory: 4
    },
    autoScaling: false,
    scaling: {
      minInstances: 1,
      maxInstances: 3
    },
    description: ''
  })
}

const handleDelete = (model) => {
  ElMessageBox.confirm(
    '确定要删除该模型吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // TODO: 实现删除功能
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleCompare = () => {
  activeTab.value = 'comparison'
}

const handleDeploy = () => {
  // TODO: 实现批量部署功能
  ElMessage.info('批量部署功能开发中...')
}

const handleAddModel = () => {
  // TODO: 实现添加模型功能
  ElMessage.info('添加模型功能开发中...')
}

const handleRemoveModel = (model) => {
  // TODO: 实现移除模型功能
  ElMessage.success('移除成功')
}

const handleExportMatrix = () => {
  // TODO: 实现导出混淆矩阵功能
  ElMessage.success('导出成功')
}

const handleExportROC = () => {
  // TODO: 实现导出ROC曲线功能
  ElMessage.success('导出成功')
}

const handleExportImportance = () => {
  // TODO: 实现导出特征重要性功能
  ElMessage.success('导出成功')
}

const handleExportComparison = () => {
  // TODO: 实现导出对比结果功能
  ElMessage.success('导出成功')
}

const handleDeploySubmit = async () => {
  if (!deployFormRef.value) return
  
  await deployFormRef.value.validate((valid) => {
    if (valid) {
      // TODO: 实现部署功能
      ElMessage.success('部署成功')
      deployDialogVisible.value = false
    }
  })
}
</script>

<style scoped>
.model-evaluation {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.evaluation-content {
  padding: 20px 0;
}

.metrics-card {
  height: 400px;
}

.confusion-matrix {
  height: 400px;
}

.matrix-container {
  height: 300px;
}

.roc-curve {
  height: 400px;
}

.curve-container {
  height: 300px;
}

.feature-importance {
  height: 400px;
}

.importance-container {
  height: 300px;
}

.comparison-content {
  padding: 20px 0;
}

.model-selection {
  margin-bottom: 20px;
}

.performance-comparison {
  height: 500px;
}

.comparison-container {
  height: 400px;
}

.mt-20 {
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-descriptions__label) {
  width: 120px;
}

:deep(.el-input-number) {
  margin-right: 10px;
}
</style> 